import java.util.Arrays;

public class TestHeap {//构造堆
    private  int []elem;
    private  int usedSize;
    public  TestHeap(){
        this.elem=new int[10];
    }
    public  void initHeap(int []array){//初始化堆
        for (int i = 0; i <array.length ; i++) {
            elem[i]=array[i];
            usedSize++;

        }

    }
    public  void createHeap(){

    }
    private  void shiftDown(int parent,int usedSize){//大根堆向下
        int child=(2*parent)+1;//左孩子下标
        while (child<usedSize){
            if(child+1<usedSize&&elem[child]<elem[child+1]){
                child++;
            }
            if(elem[child]>elem[parent]){
                swap(child,parent);
                parent=child;
                child=2*parent+1;
            }else {
                break;
            }
        }

    }
    public  void shiftUp(int child){
        int parent=(child-1)/2;
        while (child>0){
            if(elem[child]>elem[parent]){
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }

    }
    private  void swap(int i,int j){
        int tmp=elem[i];
        elem[i]=elem[j];
        elem[j]=tmp;

    }
    public  void offer(int val){
        if(isFull()){
            this.elem= Arrays.copyOf(elem,2*elem.length);//扩容
        }
        this.elem[usedSize]=val;
        usedSize++;


    }
    public  boolean isFull(){
        return usedSize==elem.length;
    }
    public  int pop(){
        int tmp=elem[0];
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
        return  tmp;
    }
    public void heapSort() {
        int end = usedSize-1;
        while (end > 0) {
            swap(0,end);
            shiftDown(0,end);
            end--;
        }
    }

}
